<template>
  <div class="inner">
    <div class="left">
      <div class="tree">
        <el-select @click.native="getCategoryList" v-model="filterText" size="small" clearable
          style="width: 95%; padding-left: 10px; margin-bottom: 10px" filterable placeholder="请选择..."
          popper-class="eloption" @change="searchFn">
          <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.name" />
        </el-select>
        <el-tree ref="tree" class="filter-tree" :expand-on-click-node="false" :highlight-current="true" node-key="id"
          :current-node-key="hId" accordion :props="defaultProps" :data="categoryList2"
          :default-expanded-keys="treeExpandedArr" @node-click="handleNodeClick">
          <span slot-scope="{ node, data }" class="custom-tree-node">
            <span style="color: black">
              {{ node.label }}({{ data.count }})
            </span>
            <span>
              <el-dropdown v-if="$showFn([
                'category_add',
                'category_edit',
                'category_del'
              ])
                " trigger="click" size="mini" style="color: black" type="text">
                <span class="el-dropdown-link">
                  <i class="el-icon-more" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-if="node.level == '1' ||
                    node.level == '2'
                    " style="color: green" @click.native.stop="
    addTreeFn(node, data)
    " v-has="'category_add'">
                    新增
                  </el-dropdown-item>
                  <el-dropdown-item style="color: blue" @click.native="editTreeFn(node, data)" v-has="'category_edit'">
                    修改
                  </el-dropdown-item>
                  <el-dropdown-item style="color: red" v-has="'category_del'" @click.native="$delFn('分类', delBtn)">
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </span>
          </span>
        </el-tree>
      </div>
      <el-button class="addBtn" v-has="'category_add'" @click="addCategory">
        新增商品分类
        <i class="el-icon-plus"></i>
      </el-button>
    </div>
    <div class="right">
      <div class="table">
        <vxe-table :column-config="{ resizable: true }" border class="tablebox" ref="xTable1"
          :row-config="{ isHover: true }" :scroll-y="{ enabled: true, gt: 21 }" align="center" style="width: 100%"
          max-height="680" size="medium">
          <vxe-column type="seq" width="80" title="序号" />
          <vxe-column field="firstCode" title="商品条码" :min-width="elTableAdaptationWidth('firstCode', selectGoodsList) + 20
            " />
          <vxe-column :min-width="elTableAdaptationWidth('name', selectGoodsList)" title="商品名称">
            <template v-slot="{ row }">
              <span style=" color: rgb(0, 42, 255)" @click.stop="detail(row)">
                {{ row.name }}</span>
            </template>
          </vxe-column>
          <vxe-column field="agreedPrice" min-width="120" title="协议进价（元）" />
          <vxe-column field="outboundPrice" min-width="120" title="出仓价（元）" />
          <vxe-column field="standard" title="规格" min-width="100"/>
          <vxe-column field="unitName" title="单位" width="100"/>
          <vxe-column field="brandName" title="品牌" min-width="150"/>
          <vxe-column field="producer" title="产地" min-width="150"/>
          <vxe-column v-if="$showFn(['category_move'])" width="100" title="操作" fixed="right">
            <template v-slot="{ row }">
              <el-button type="text" @click.stop="moveFn(row)" v-has="'category_move'">
                移动
              </el-button>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="pagination">
        <el-pagination :current-page="page.pageNum" background :page-sizes="$pageSizes" :page-size="page.pageSize"
          layout="total, ->,sizes, prev, pager, next, jumper" :total="page.total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
    <!-- 新增/修改分类弹窗 -->
    <el-dialog :close-on-click-modal="false" :title="dTitle" width="30%" :visible.sync="dialogFormVisible"
      @close="btnClose">
      <el-form ref="addForm" @submit.native.prevent :model="categoryFormData" :rules="addRules" label-position="left"
        label-width="auto">
        <el-form-item label="分类名称" prop="name">
          <el-input v-clearEmoji v-model="categoryFormData.name" placeholder="请输入..." type="text" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button class="celBtn" @click="btnClose">取 消</el-button>
        <el-button class="addBtn" type="primary" @click="btnOk">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 移动商品分类弹窗 -->
    <el-dialog :close-on-click-modal="false" :title="dTitle" width="35%" :visible.sync="diaMove" @close="cancelMove">
      <el-form ref="moveForm" :model="moveForm" :rules="moveRules">
        <el-row :gutter="24">
          <el-col :span="20">
            <el-form-item label="目标分类" label-width="80px" prop="categoryId">
              <el-cascader style="width: 100%" ref="cascaderRef" v-model.trim="moveForm.categoryId"
                :props="movedefaultProps" :options="categoryList2" filterable @change="handleChange" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button class="celBtn" @click="cancelMove">取 消</el-button>
        <el-button class="addBtn" @click="moveOk">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { debounce } from 'lodash'
import {
  getCategoryList,
  getCategoryTreeList,
  addCategory,
  updateCategory,
  selectGoodsList,
  updateGoodsCategory,
  delCategory
} from '@/api/goods';
// import { transListToTreeData } from '@/utils'
// import { rsaDecrypt } from '@/utils/commonUtil3'
export default {
  name: 'GoodsCategory',
  data() {
    return {
      diaMove: false,
      state: '',
      hId: '',
      timeout: null,
      handleNodeClickId: '', // 点击el-tree的节点ID
      handleNodeClickLevel: '', // 点击el-tree的节点level
      treeExpandedArr: [], // 需要展开的节点id数组
      filterText: '',
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      categoryList: [],
      categoryList2: [],
      dialogFormVisible: false, // 新增/修改分类弹窗
      categoryFormData: {
        level: '1',
        name: '',
        parentId: '0',
        id: ''
      },
      addRules: {
        name: [
          {
            required: true,
            message: '分类名不能为空',
            trigger: 'blur'
          },
          {
            // pattern 正则表达式
            pattern:
              /^(?:[\u3400-\u4DB5\u4E00-\u9FEA\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29]|[\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0])+$/,
            message: '分类名只能是汉字',
            trigger: 'blur'
          },
          {
            min: 0,
            max: 10,
            message: '分类名最长为10位',
            trigger: 'blur'
          }
        ]
      },
      dTitle: '新增', // 弹窗标题
      delContent: '确认要删除该分类吗？',
      delDialogVisible: false, // 删除弹窗
      selectGoodsList: [], // 商品列表
      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0
      },
      movedefaultProps: {
        children: 'children',
        label: 'name',
        emitPath: false,
        value: 'id'
      },
      // 移动分类弹窗表单
      moveForm: {
        categoryId: '',
        commodityIdList: []
      },
      moveRules: {
        categoryId: [
          {
            required: true,
            message: '请选择分类',
            trigger: 'blur'
          }
        ]
      },
      goodsContrastVisible: false, // 商品对比弹窗
      notSelectGoodsList: [], // 未分类列表
      sKeywords: '', // 搜索关键字
      noCategoryCount: ''
    };
  },
  created() {
    this.getCategoryList();
    this.getCategoryTreeList();
  },
  methods: {
    async getCategoryList() {
      const res = await getCategoryList();
      if (res.code === 200) {
        this.categoryList = res.data.categoryList;
        console.log('categoryList', this.categoryList);
      }
      console.log(res);
    },
    async getCategoryTreeList() {
      const res = await getCategoryTreeList();
      if (res.code === 200) {
        this.categoryList2 = res.data.categoryList;
        console.log('categoryList2', this.categoryList2);
        if (this.categoryList2.length > 0) {
          // console.log('0000000000000000000');
          this.$nextTick(() => {
            this.$refs.tree.setCurrentKey(this.categoryList2[0].id);
          });
          this.handleNodeClickId = this.categoryList2[0].id;
          this.handleNodeClickLevel = this.categoryList2[0].level;
          this.getselectGoodsList(
            this.categoryList2[0].id,
            this.categoryList2[0].level
          );
        }
        // console.log(' this.handleNodeClickId', this.handleNodeClickId, this.handleNodeClickLevel);
      }
      console.log(res);
    },
    async getselectGoodsList(categoryId, categoryLevel) {
      const res = await selectGoodsList({
        ...this.page,
        categoryId,
        categoryLevel
      });
      if (res.code === 200) {
        const result = res.data;
        console.log('selectGoodsList', result);
        this.selectGoodsList = result.list;
        this.page.pageSize = result.pageSize;
        this.page.pageNum = result.pageNum;
        this.page.total = result.total;
        const $table = this.$refs.xTable1
        $table.loadData(this.selectGoodsList);
        console.log('selectGoodsList', this.selectGoodsList);
      } else {
        // this.$message.error(res.message);
      }
      console.log(res);
    },
    // 搜索框事件
    searchFn(val) {
      // let obj = {}
      // 找到选中项的整个object对象
      const obj = this.categoryList.find(item => {
        return item['name'] === val;
      });
      console.log(obj, 'obj');
      this.filterText = obj.name;
      for (const key in this.$refs.tree.store.nodesMap) {
        this.$refs.tree.store.nodesMap[key].expanded = false;
      }
      // console.log('搜索', obj)
      if (obj.id) {
        this.treeExpandedArr = [obj.id];
        this.hId = obj.id;
        this.handleNodeClick(obj);
        this.$refs.tree.setCurrentKey(obj.id);
      }
    },
    // 点击el-tree的节点
    handleNodeClick(node) {
      this.handleNodeClickId = node.id;
      this.handleNodeClickLevel = node.level;
      // console.log(node.id)
      this.page.pageNum = 1;
      this.page.pageSize = 20;
      this.getselectGoodsList(node.id, node.level);
    },
    // 节点增加
    addTreeFn(node, data) {
      this.dialogFormVisible = true;
      this.dTitle = '新增';
      this.categoryFormData.level = +data.level + 1;
      console.log(data);
      console.log(this.categoryFormData.level);
      this.categoryFormData.parentId = data.id;
    },
    // 修改节点
    editTreeFn(node, data) {
      console.log('修改editTreeFn');
      this.dialogFormVisible = true;
      this.dTitle = '修改';
      this.categoryFormData.level = data.level;
      this.categoryFormData.name = data.name;
      this.categoryFormData.id = data.id;
    },
    // 删除节点
    // async delTreeFn(node, data) {
    //   console.log('删除delTreeFn');
    //   // console.log(this.handleNodeClickId)
    //   // console.log(node)
    //   this.delDialogVisible = true;
    // },
    // 删除分类
    async delBtn() {
      console.log(this.handleNodeClickId, this.handleNodeClickLevel);
      const res = await delCategory({
        id: this.handleNodeClickId,
        level: this.handleNodeClickLevel
      });
      if (res.code === 200) {
        this.$message.success('删除成功');
        this.getCategoryList();
        this.getCategoryTreeList();
        this.delDialogVisible = false;
      } else {
        // this.$message.error(res.message);
        this.delDialogVisible = false;
      }
    },
    // 左侧添加商品分类
    addCategory() {
      this.dialogFormVisible = true;
      this.dTitle = '新增';
    },
    btnOk() {
      this.$refs.addForm.validate(async isOk => {
        if (isOk) {
          if (this.dTitle === '新增') {
            const res = await addCategory(this.categoryFormData);
            console.log(res);
            if (res.code === 200) {
              this.$message.success('添加成功');
              this.dialogFormVisible = false;
              this.treeExpandedArr.push(this.categoryFormData.id);
              this.getCategoryList();
              this.getCategoryTreeList();
            } else {
              // this.$message.error(res.message);
              this.dialogFormVisible = false;
            }
          } else if (this.dTitle === '修改') {
            // console.log()
            const res = await updateCategory(this.categoryFormData);
            console.log('修改', res);
            if (res.code === 200) {
              this.$message.success('修改成功');
              this.dialogFormVisible = false;
              this.treeExpandedArr.push(this.categoryFormData.id);
              this.getCategoryList();
              this.getCategoryTreeList();
            } else {
              // this.$message.error(res.message);
              this.dialogFormVisible = false;
            }
          }
          this.categoryFormData.level = '1';
          this.categoryFormData.name = '';
          this.categoryFormData.parentId = '0';
          this.categoryFormData.id = '';
        } else {
          this.$message.warning('请检查输入信息');
        }
      });
    },
    btnClose() {
      this.$refs.addForm.resetFields();
      this.categoryFormData.level = '1';
      this.categoryFormData.name = '';
      this.categoryFormData.parentId = '0';
      this.dialogFormVisible = false;
    },
    // 获取条数改变
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.page.pageNum = 1;
      console.log(`每页 ${val} 条`);
      console.log(this.handleNodeClickId,
        this.handleNodeClickLevel, 'id')
      this.getselectGoodsList(
        this.handleNodeClickId,
        this.handleNodeClickLevel
      );
    },
    // 获取页数改变
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page.pageNum = val;
      console.log(this.handleNodeClickId,
        this.handleNodeClickLevel, 'id')
      this.getselectGoodsList(
        this.handleNodeClickId,
        this.handleNodeClickLevel
      );
    },
    moveFn(row) {
      // this.dTitle = '移动分类';
      console.log('move', row);
      this.diaMove = true;
      this.moveForm.commodityIdList.push(row.id);
    },
    // 移动分类
    async moveOk() {
      console.log('moveOk');
      // 调用移动分类接口
      this.$refs.moveForm.validate(async isOk => {
        if (isOk) {
          const res = await updateGoodsCategory(this.moveForm);
          console.log('moveForm', this.moveForm);
          if (res.code === 200) {
            this.$message.success('移动成功');
            this.diaMove = false;
            this.moveForm.commodityIdList = [];
            this.moveForm.categoryId = '';
            this.treeExpandedArr.push(this.handleNodeClickId);
            this.$nextTick(() => {
              this.hId = this.handleNodeClickId;
              this.$refs['tree'].setCurrentKey(this.hId);
            });
            if (
              this.selectGoodsList.length === 1 &&
              this.page.pageNum > 1
            )
              this.page.pageNum--;
            this.getselectGoodsList(
              this.handleNodeClickId,
              this.handleNodeClickLeve
            );
            this.getCategoryTreeList();
          } else {
            // this.$message.error(res.message);
          }
          console.log(res);
          // 关闭弹窗，清空表单
        } else {
          this.$message.warning('请选择三级分类');
        }
      });
    },
    // 分类选择后
    handleChange(value) {
      console.log('分类', value);
      const nodes = this.$refs.cascaderRef.getCheckedNodes();
      console.log('nodes', nodes);
      if (nodes[0]?.level === 3) {
        this.moveForm.categoryId = value;
        this.handleNodeClickId = value;
        this.handleNodeClickLeve = '3';
        console.log('ok', this.moveForm.categoryId);
      } else {
        this.moveForm.categoryId = '';
        // this.categoryId = ''
        console.log('no', this.moveForm.categoryId);
        this.$message.error('请选择三级分类');
      }
    },
    // 新增商品对照
    cancelMove() {
      this.diaMove = false;
      this.moveForm.commodityIdList = [];
      this.moveForm.categoryId = '';
    },
    detail(row) {
      this.$router.push({
        path: "goodsDetail",
        query: {
          type: "detail",
          id: row.id,
        },
      });
    },
  }
};
</script>

<style lang="scss" scoped>
.inner {
  display: flex;
  height: 100%;

  .left {
    width: 280px;
    padding: 16px;
    height: 100%;
    border-right: 1px solid #e7e7e7;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .select {
      margin-bottom: 20px;
    }

    .addBtn {
      width: 100%;
      background-color: #0052D9;
      color: #fff
    }
  }

  .right {
    padding: 20px;
    height: 100%;
    // width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    flex: 1;
    width: 300px;

    .table {
      // flex: 1;
      width: 100%;
    }
  }
}
</style>
<style>
.custom-tree-node {
  flex: 1;
  width: 240px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  color: #a09e9e;
}

.el-tree {
  max-height: 600px;
  overflow-y: auto;
}
</style>
